<template>
  <BasicDrawer v-bind="$attrs" :title="getTitle" width="50%" @register="register">
    <div>
      <BasicForm @register="registerForm" />
    </div>
  </BasicDrawer>
</template>
<script lang="ts" name="DrawerForm" setup>
  import { computed, ref } from 'vue';

  import { createDevices, updateDevices } from '@/api/page/unit_type';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { useMessage } from '@/hooks/web/useMessage';

  import { schemas } from '../data';

  const { createMessage } = useMessage();

  const getTitle = computed(() => title.value);
  const title = ref<string>('');
  const details = ref<object>({});
  const emit = defineEmits(['next', 'register']);
  const [registerForm, { setFieldsValue, updateSchema, validate, resetFields }] = useForm({
    schemas,
    layout: 'vertical',
    actionColOptions: {
      span: 24,
    },
    showResetButton: false,
    showSubmitButton: title.value === '详情' ? false : true,
    submitButtonOptions: {
      text: '提交',
    },
    submitFunc: customSubmitFunc,
  });
  const [register, { closeDrawer }] = useDrawerInner((data) => {
    resetFields();
    title.value = data.title;
    details.value = data.record || {};
    if (data?.details) {
      updateSchema(
        schemas.map((item) => ({
          field: item.field,
          componentProps: {
            disabled: true,
          },
        })),
      );
    } else {
      updateSchema(
        schemas.map((item) => ({
          field: item.field,
          componentProps: {
            disabled: false,
          },
        })),
      );
    }

    data.record &&
      setFieldsValue({
        ...data.record,
      });
  });

  async function customSubmitFunc() {
    try {
      const values = await validate();
      if (title.value === '添加') {
        createDevices(values).then((res) => {
          if (res.code === 1000) {
            createMessage.success('添加成功！');
            emit('next', values);
          } else {
            console.log('res :>> ', res);
            createMessage.error(res.msg);
          }
        });
      } else {
        const params = Object.assign({}, details.value, values);
        updateDevices(params).then((res) => {
          if (res.code === 1000) {
            createMessage.success('修改成功！');
            emit('next', values);
          } else {
            createMessage.error(res.msg);
          }
        });
      }
      closeDrawer();
    } catch (error) {
      console.log('error', error);
      createMessage.error('请将有红色标记的填写完整');
    }
  }
</script>
<style scoped>
  :deep(.ant-form-item-control) {
    padding: 0 10px;
  }
</style>
